import ccclass = cc._decorator.ccclass;
import property = cc._decorator.property;
import {globalConfig} from "../config/globalConfig";
import {getItem, getReward} from "../config/config";

@ccclass
export class LuckyProbability extends cc.Component {
  @property(cc.Prefab)
  labelPrefab: cc.Prefab = null
  @property(cc.Node)
  layout1: cc.Node = null
  @property(cc.Node)
  layout2: cc.Node = null

  onLoad() {
    const total = globalConfig.turntable.reduce((pre: Array<number>, value: any) => {
      return [pre[0] + value.goldWeight, pre[1] + value.diamondWeight]
    }, [0, 0])
    globalConfig.turntable.forEach((config: any) => {
      const rewardConfig: any = getReward(config.reward)
      const itemConfig: any = getItem(rewardConfig.itemid)
      const node1 = this.setLabelNode(itemConfig.name + 'x' + rewardConfig.number, config.goldWeight / total[0])
      this.layout1.addChild(node1)
      const node2 = this.setLabelNode(itemConfig.name + 'x' + rewardConfig.number, config.diamondWeight / total[1])
      this.layout2.addChild(node2)
    })
  }

  private setLabelNode(name: string, probability: number) {
    const labelNode = cc.instantiate(this.labelPrefab)
    labelNode.getChildByName('labelName').getComponent(cc.Label).string = name
    labelNode.getChildByName('labelProbability').getComponent(cc.Label).string = Math.floor(probability * 100) + '%'
    return labelNode
  }

  onClose() {
    this.node.destroy()
  }
}